#include "../../include/machine/CJsonOper.h"
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include <strstream>

using namespace boost::property_tree;

CJsonOper::CJsonOper()
{
}

CJsonOper::~CJsonOper()
{
}

//获取命令，若失败返回空
int CJsonOper::GetCMD(std::string src)
{
    std::stringstream st(src);
    ptree pt;

    try
    {
        read_json<ptree>(st,pt);
        std::string cmd = pt.get_child("cmd").data();
        if(cmd.length()> 0)
        {
            if(cmd.compare("update") ==0)
                return CMD_UPDATE_MACHINE_DATA;
            else
            {
                errMsg = "未指定的命令";
                return CMD_ERROR;  
            }
        }
        else
        {
            errMsg = "命令为空";
            return CMD_ERROR;    
        }
    }
    catch(std::exception& e)
    {
        errMsg = "json数据解析失败,";
        errMsg += e.what();
        return CMD_ERROR;
    }
 
    return CMD_ERROR;
}

//获取机器数据
bool CJsonOper::GetMachData(std::string src,unsigned int &mach_id,CMachineData &data_out)
{
    /*
    {
	    "cmd": "UPDATE",
	    "machineID": 1,
	    "status": 1,
	    "prgname": "xxxx",
	    "output": 20,
	    "cycletime": 12.2,
	    "alarmcode": "",
	    "alarmmsg": "",
        "recordtime":"2020-12-22 11:11:11"
    }
    */
    std::stringstream st(src);
    ptree pt;

    try
    {
        read_json<ptree>(st,pt);
        std::string strTemp = "";

        //machine_id
        strTemp = pt.get_child("machineID").data();
        mach_id = atoi(strTemp.c_str());

        //status
        strTemp = pt.get_child("status").data();
        data_out.machStatus = atoi(strTemp.c_str());

	    //prgname
        data_out.prgName = pt.get_child("prgname").data();

	    //output
        strTemp = pt.get_child("output").data();
        data_out.machOutput = atoi(strTemp.c_str());

	    //cycletime
        strTemp = pt.get_child("cycletime").data();
        data_out.cycleTime = atof(strTemp.c_str());

	    //alarmcode
        data_out.alarmCode = pt.get_child("alarmcode").data();

	    //alarmmsg
        data_out.alarmMsg = pt.get_child("alarmmsg").data();       

        //recordtime
        data_out.recordTime = pt.get_child("recordtime").data();       
    }
    catch(std::exception& e)
    {
        errMsg = "json数据解析失败,";
        errMsg += e.what();
        return false;
    }
 
    return true;
}

//通用正常返回包
std::string CJsonOper::GenUniversalOK(void)
{
    std::stringstream st;
    ptree pt;
    pt.put("cmd","ret");
    pt.put("ret",1);
    pt.put("msg","");
    write_json(st,pt);
    return st.str();
}   

//通用异常返回包
std::string CJsonOper::GenUniversalNG(std::string err)
{
    std::stringstream st;
    ptree pt;
    pt.put("cmd","ret");
    pt.put("ret",0);
    pt.put("msg",err);
    write_json(st,pt);
    return st.str();
}

//获取错误信息
std::string CJsonOper::GetErrMsg(void)
{
    return errMsg;
}